<template>
  <div class="app-container">
    <el-row :gutter="20" class="div-height-left">
      <el-col v-if="userInfo.userId === '1'" :span="4" class="div-height-left">
        <sys-org-tree @treeClick="treeClick" />
      </el-col>
      <el-col :span="userInfo.userId === '1' ? 20 : 24" :xs="24">
        <div class="search-container">
          <el-form
            v-show="showSearch"
            ref="queryParamsRef"
            :inline="true"
            :model="queryParams"
            label-width="100px"
          >
            <el-form-item label="诊疗项目分类" prop="itemClass">
              <el-select
                v-model="queryParams.itemClass"
                clearable
                placeholder="请选择诊疗项目分类"
                style="width: 160px"
                @change="getList"
              >
                <el-option
                  v-for="dict in dictDataMap['bill_item_class_dict']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="诊疗代码" prop="itemCode">
              <el-input
                v-model="queryParams.itemCode"
                clearable
                placeholder="请输入诊疗代码"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="诊疗项目名称" prop="itemName">
              <el-input
                v-model="queryParams.itemName"
                clearable
                placeholder="请输入诊疗项目名称"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="执行科室" prop="performedBy">
              <el-input
                v-model="queryParams.performedBy"
                clearable
                placeholder="请输入执行科室"
                style="width: 100%"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <div class="mr20" style="float: right">
              <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery" />
            </div>
          </el-form>
        </div>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-hasPerm="['base:clinicItemDict:add']"
              :disabled="!queryParams.orgId"
              iplain
              type="primary"
              @click="handleAdd"
            >
              <template #icon>
                <i-ep-plus />
              </template>
              新增
            </el-button>
          </el-col>
          <!--                    <el-col :span="1.5">-->
          <!--                        <el-button-->
          <!--                            type="success"-->
          <!--                            plain-->
          <!--                            icon="el-icon-edit"-->
          <!--                           -->
          <!--                            :disabled="single"-->
          <!--                            @click="handleUpdate"-->
          <!--                            v-hasPerm="['base:clinicItemDict:edit']"-->
          <!--                        >修改-->
          <!--                        </el-button>-->
          <!--                    </el-col>-->
          <!--                    <el-col :span="1.5">-->
          <!--                        <el-button-->
          <!--                            type="danger"-->
          <!--                            plain-->
          <!--                            icon="el-icon-delete"-->
          <!--                           -->
          <!--                            :disabled="multiple"-->
          <!--                            @click="handleDelete"-->
          <!--                            v-hasPerm="['base:clinicItemDict:remove']"-->
          <!--                        >删除-->
          <!--                        </el-button>-->
          <!--                    </el-col>-->
          <el-col :span="1.5">
            <el-button
              v-hasPerm="['base:clinicItemDict:export']"
              :disabled="!queryParams.orgId"
              icon="el-icon-download"
              plain
              type="warning"
              @click="handleExport"
              >导出
            </el-button>
          </el-col>
        </el-row>

        <el-table
          v-adaptive
          :border="true"
          :data="ClinicItemDictList"
          :header-cell-style="$headerCellStyle"
          :stripe="true"
          highlight-current-row
          @selection-change="handleSelectionChange"
        >
          <el-table-column :align="'center'" type="selection" width="55" />
          <el-table-column
            :align="'left'"
            label="诊疗项目分类"
            prop="itemClass"
            width="100px"
          >
            <template #default="scope">
              <dict-data-tag
                :options="dictDataMap['bill_item_class_dict']"
                :value="scope.row.itemClass"
              />
            </template>
          </el-table-column>
          <el-table-column
            :align="'left'"
            :show-overflow-tooltip="true"
            label="诊疗项目代码"
            min-width="100px"
            prop="itemCode"
          />
          <el-table-column
            :align="'left'"
            :show-overflow-tooltip="true"
            label="诊疗项目名称"
            min-width="180px"
            prop="itemName"
          />
          <el-table-column
            :align="'left'"
            :show-overflow-tooltip="true"
            label="诊疗项目规格"
            min-width="180px"
            prop="itemSpec"
          />
          <el-table-column
            :show-overflow-tooltip="true"
            label="总价(元)"
            prop="subTotal"
            width="120"
          >
            <template #default="scope">
              <span class="ys-css">{{ parseFloat(scope.row.subTotal).toFixed(2) }}</span
              >元
            </template>
          </el-table-column>
          <el-table-column :align="'left'" label="执行科室" prop="performedByName" />
          <el-table-column :align="'center'" label="注意事项" prop="isMeal">
            <template #default="scope">
              <dict-data-tag
                :options="dictDataMap['matters_needing_attention']"
                :value="scope.row.isMeal"
              />
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="排序" prop="sort" />
          <el-table-column
            :align="'center'"
            :show-overflow-tooltip="true"
            label="备注信息"
            prop="remark"
          />
          <el-table-column
            :align="'left'"
            class-name="small-padding fixed-width"
            label="操作"
            width="280px"
          >
            <template #default="scope">
              <template v-if="scope.row.itemClass !== 'A' && scope.row.itemClass !== 'B'">
                <el-button
                  v-hasPerm="['base:clinicItemDict:addControl']"
                  type="success"
                  @click="addControl(scope.row)"
                >
                  <template #icon>
                    <i-ep-edit />
                  </template>
                  添加对照
                </el-button>
                <el-button
                  v-hasPerm="['base:clinicItemDict:edit']"
                  type="success"
                  @click="handleUpdate(scope.row)"
                >
                  <template #icon>
                    <i-ep-edit />
                  </template>
                  修改
                </el-button>
                <el-button
                  v-hasPerm="['base:clinicItemDict:remove']"
                  type="danger"
                  @click="handleDelete(scope.row)"
                >
                  <template #icon>
                    <i-ep-delete />
                  </template>
                  删除
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          v-model:limit="queryParams.pageSize"
          v-model:page="queryParams.pageNum"
          :total="total"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 添加或修改诊疗项目对话框 -->
    <el-dialog
      v-model="open"
      :close-on-click-modal="false"
      :title="title"
      append-to-body
      width="900px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="40">
          <el-col :span="12"></el-col>
          <el-col :span="12">
            <el-form-item label="诊疗项目分类" prop="itemClass">
              <el-select
                v-model="form.itemClass"
                placeholder="请选择诊疗项目分类"
                style="width: 100%"
                @change="itemClassChange"
              >
                <el-option
                  v-for="dict in billItemList"
                  :key="dict.dictValue"
                  :disabled="dict.disabled"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行科室">
              <base-dept-tree
                :org-id="queryParams.orgId"
                :value="form.performedBy"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="诊疗代码" prop="itemCode">
              <el-input v-model="form.itemCode" placeholder="请输入诊疗代码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="诊疗项目名称" prop="itemName">
              <el-input
                v-model="form.itemName"
                placeholder="请输入诊疗项目名称"
                @input="itemNameInput"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="诊疗项目规格">
              <el-input v-model="form.itemSpec" placeholder="请输入诊疗项目规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="isOperation" label="手术名称" prop="operationName">
              <el-input
                v-model="form.operationName"
                placeholder="请输入手术名"
                @blur="operationIdBlur"
                @focus="operationIdFocus"
                @input="operationIdInput"
              />
              <el-popover
                v-model="visible"
                placement="bottom"
                title="选择项目"
                trigger="manual"
                width="650"
              >
                <el-table
                  :border="true"
                  :data="operationItemData"
                  :stripe="true"
                  highlight-current-row
                  @row-click="rowClick"
                >
                  <el-table-column
                    :show-overflow-tooltip="true"
                    label="手术代码"
                    property="operationCode"
                    width="110"
                  ></el-table-column>
                  <el-table-column
                    :show-overflow-tooltip="true"
                    label="手术名称"
                    property="operationName"
                    width="230"
                  ></el-table-column>
                  <el-table-column
                    :align="'center'"
                    :show-overflow-tooltip="true"
                    label="手术等级"
                    prop="operationScale"
                  >
                    <template #default="scope">
                      <dict-data-tag
                        :options="dictDataMap['operation_grade']"
                        :value="scope.row.operationScale"
                      />
                    </template>
                  </el-table-column>
                </el-table>
                <el-button style="float: right; margin-top: 5px" @click="closePopover">
                  关闭
                </el-button>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="isOperation" label="手术等级" prop="operationRegiste">
              <el-select
                v-model="form.operationRegiste"
                filterable
                placeholder="请选择手术等级"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dictDataMap['operation_grade']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拼音码" prop="inputCode">
              <el-input v-model="form.inputCode" placeholder="请输入拼音码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="icd9名称" prop="icd9Name">
              <el-input v-model="form.icd9Name" placeholder="请输入icd9名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="icd9编码" prop="icd9Code">
              <el-input v-model="form.icd9Code" placeholder="请输入icd9编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注意事项">
              <el-select
                v-model="form.isMeal"
                clearable
                placeholder="请选择诊疗项目分类"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dictDataMap['matters_needing_attention']"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扩展字段1">
              <el-input v-model="form.expand1" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扩展字段2">
              <el-input v-model="form.expand2" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扩展字段3">
              <el-input v-model="form.expand3" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扩展字段4">
              <el-input v-model="form.expand4" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扩展字段5">
              <el-input v-model="form.expand5" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注信息" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入内容" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
    <add-control-dialog ref="addControlDialogRef" @selectClinicList="getList" />
  </div>
</template>

<script lang="ts" setup>
import {
    addClinicItemDict,
    delClinicItemDict,
    getClinicItemDict,
    selectPageClinicItemDict,
    updateClinicItemDict,
} from "@/api/base/clinicItemDict";
import addControlDialog from "@/views/base/clinicItemDict/addControlDialog.vue";
import {listDept} from "@/api/system/dept";
import {getOperationAuto, getOperationDict} from "@/api/base/operationDict";
import baseDeptTree from "@/components/Dept/baseDeptTree.vue";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {firstLetterResult} from "@/utils/pinyin";

const useUserStore = useUserStoreHook();
const { proxy } = getCurrentInstance() as any;
const dictStore = useDictStoreHook();
const formRef = ref();
const addControlDialogRef = ref();
const dictDataMap = ref(
  dictStore.isTypeGetData(
    "bill_item_class_dict",
    "matters_needing_attention",
    "operation_grade",
    "operation_grade"
  )
);
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 诊疗项目表格数据
const ClinicItemDictList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 科室树选项
const deptOptions = ref([]);
// 检查项目是否为手术
const isOperation = ref(false);
// 诊疗项目下拉框
const billItemList = ref<any[]>([]);
// 手术项目自动补全查询条件
const itemInfo = ref("");
// 手术项目选择框
const visible = ref(false);
// 查询到的手术项目
const operationItemData = ref([]);
// 科室信息翻译
const listDeptRef = ref([]);
// 查询参数
const queryParamsRef = ref();
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  itemClass: undefined,
  itemCode: undefined,
  itemName: undefined,
  performedBy: undefined,
  inputCode: undefined,
  orgId: undefined,
  expand1: undefined,
  expand2: undefined,
  expand3: undefined,
  expand4: undefined,
  expand5: undefined,
  isMeal: undefined,
  sort: undefined,
  icd9Name: undefined,
  icd9Code: undefined,
  operationId: undefined,
  operationRegiste: undefined,
});
// 表单参数
const form = ref<any>({
  itemInfo: "",
  operationRegiste: "",
  operationId: "",
  operationName: "",
});
// 表单校验
const rules = ref({
  clinicItemId: [{ required: true, message: "主键不能为空", trigger: "blur" }],
  itemClass: [{ required: true, message: "诊疗项目分类不能为空", trigger: "change" }],
  itemCode: [{ required: true, message: "诊疗代码不能为空", trigger: "blur" }],
  itemName: [{ required: true, message: "诊疗项目名称不能为空", trigger: "blur" }],
  performedBy: [{ required: true, message: "执行科室不能为空", trigger: "blur" }],
  inputCode: [{ required: true, message: "拼音码不能为空", trigger: "blur" }],
  operationName: [{ required: true, message: "手术名称不能为空", trigger: "blur" }],
  operationRegiste: [{ required: true, message: "手术等级不能为空", trigger: "change" }],
});

if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId;
  nextTick(function () {
    getDeptTree();
  });
  getList();
}

/** 左侧科室树节点点击事件 */
function treeClick(obj) {
  queryParams.value.orgId = obj.id;
  nextTick(function () {
    getDeptTree();
  });
  getList();
}

/** 检查项目选择事件 */
function itemClassChange(val, operationDictId) {
  if (val === "F") {
    isOperation.value = true;
    getOperationDict(operationDictId).then((res: any) => {
      if (res.data) {
        form.value.operationName = res.data.operationName;
        form.value.itemInfo = res.data.operationName;
        open.value = true;
      }
    });
  } else {
    isOperation.value = false;
    open.value = true;
  }
}

/** 项目名称输入框改变事件 设置拼音码*/
function itemNameInput(value) {
  if (value) {
    form.value.inputCode = firstLetterResult(value);
  } else {
    form.value.inputCode = "";
  }
}

/** 查询科室下拉树结构 */
function getDeptTree() {
  listDept({ delFlag: "0", status: "0", orgId: queryParams.value.orgId }).then(
    (response) => {
      listDeptRef.value = response.data;
      if (form.value.deptId) {
        let index = Array.from(response.data).findIndex((item: any) => {
          return (item.deptId = form.value.deptId);
        });
        if (index === -1) {
          form.value.deptId = undefined;
        }
      }
      deptOptions.value = proxy.$handleTree(response.data, "deptId", "deptName");
    }
  );
}

/** 查询诊疗项目列表 */
function getList() {
  if (!queryParams.value.orgId) {
    return ElMessage.error("请先选择左侧所属机构后查询");
  }
  selectPageClinicItemDict(queryParams.value).then((response: any) => {
    let rows = response.rows;
    rows.forEach((item) => {
      // 科室翻译
      listDeptRef.value.forEach((dept: any) => {
        if (item.performedBy === dept.deptId) {
          item.performedByName = dept.deptName;
        }
      });
    });
    ClinicItemDictList.value = rows;
    total.value = response.total;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    clinicItemId: undefined,
    itemClass: undefined,
    itemCode: undefined,
    itemName: undefined,
    performedBy: undefined,
    inputCode: undefined,
    expand1: undefined,
    expand2: undefined,
    expand3: undefined,
    expand4: undefined,
    expand5: undefined,
    delFlag: undefined,
    createBy: undefined,
    createTime: undefined,
    updateBy: undefined,
    updateTime: undefined,
    remark: undefined,
    isMeal: undefined,
    sort: undefined,
    icd9Name: undefined,
    icd9Code: undefined,
    operationId: undefined,
    operationRegiste: undefined,
    orgId: queryParams.value.orgId,
  };
  disposeAddBillItemList();
}

/** 处理新增页面诊疗项目分类数据 */
function disposeAddBillItemList() {
  billItemList.value = [];
  dictDataMap.value["bill_item_class_dict"].forEach((item) => {
    let billItem: any = {};
    if (item.dictValue === "A" || item.dictValue === "B") {
      billItem.disabled = true;
    }
    billItem.dictValue = item.dictValue;
    billItem.dictLabel = item.dictLabel;
    billItemList.value.push(billItem);
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item) => item.clinicItemId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getDeptTree();
  open.value = true;
  title.value = "添加诊疗项目";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getDeptTree();
  const clinicItemId = row.clinicItemId || ids.value;
  getClinicItemDict(clinicItemId).then((response) => {
    form.value = response.data;
    title.value = "修改诊疗项目";
    itemClassChange(response.data.itemClass, response.data.operationId);
  });
}

/** 添加对照 */
function addControl(row) {
  addControlDialogRef.value.addControlDialogShow(row);
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      if (form.value.clinicItemId != null) {
        updateClinicItemDict(form.value)
          .then((_response) => {
            ElMessage.success("修改成功");
            open.value = false;
            getList();
          })
          .finally(() => {});
      } else {
        addClinicItemDict(form.value)
          .then((_response) => {
            ElMessage.success("修新增成功");
            open.value = false;
            getList();
          })
          .finally(() => {});
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const clinicItemIds = row.clinicItemId || ids.value;
  ElMessageBox.confirm('是否确认删除诊疗项目编号为"' + clinicItemIds + '"的数据项？', {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delClinicItemDict(clinicItemIds).then(() => {
        getList();
        ElMessage.success("删除成功");
      });
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  // this.download('admin/clinicItemDict/export', {
  //     ...this.queryParams
  // }, `clinicItemDict_${new Date().getTime()}.xlsx`)
}

/** 手术项目名称失去焦点事件 */
function operationIdBlur() {
  visible.value = false;
}

/** 手术项目名称获取焦点事件 */
function operationIdFocus() {
  visible.value = true;
  getOperationAutoList();
}

/** 手术项目名称自动补全检索 */
function operationIdInput(value) {
  form.value.itemInfo = value.trim();
  getOperationAutoList();
}

/** 手术项目自动补全 */
function getOperationAutoList() {
  if (form.value.itemInfo) {
    let data = {
      orgId: queryParams.value.orgId,
      itemInfo: form.value.itemInfo,
    };
    getOperationAuto(data).then((res) => {
      operationItemData.value = res.data;
    });
  } else {
    operationItemData.value = [];
  }
}

/** 手术项目选择关闭事件 */
function closePopover() {
  visible.value = false;
  operationItemData.value = [];
}

/** 手术项目自动补全列表行点击事件 */
function rowClick(row, _column, _event) {
  form.value.operationId = row.operationDictId;
  form.value.operationName = row.operationName;
  form.value.operationRegiste = row.operationScale;
  operationItemData.value = [];
}
</script>
<script lang="ts">
export default {
  name: "ClinicItemDict",
};
</script>
